/*  header-comment
/*  file   : /Users/allan/Desktop/workSpace/react-hrm-h5/src/modules/leaveJobDelete/index
/*  author : lewin
/*  date   : 2017-10-26
/*  last   : 2017-11-2
*/
import React, { Component } from "react";
import PropTypes from "prop-types";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import { Button, TextareaItem, Icon } from "@ali/ding-ui";
import { createForm } from "rc-form";

// actions
import { getAllLeaveReasons, leaveJobAndDelete, getLeaveAndDeleteData } from "../../actions/growth/";

// utils
import {
  setTitle,
  setRight,
  toast,
  complexPicker,
  confirm,
  close,
  notify
} from "../../utils/dingtalk.js";
import { validator, showMessage } from "../../utils/form.js";
import { get } from "../../utils/db.js";

// less
import "./index.less";
import "../steps/steps.less";

// components
import Select from "../../components/Select/";
import DatePicker from "../../components/DatePicker/";
import InputItem from "../../components/InputItem/";

// 将store注入组件的props
const mapStateToProps = state => ({ welcome: state.WELCOME_USER });
// 将action与dispatch进行绑定并注入组件的props
const mapDispatchToProps = dispatch => ({
  // 区分绑定到props的action与传递的props
  actions: bindActionCreators(
    {
      dispatch,
      getAllLeaveReasons,
      leaveJobAndDelete,
      getLeaveAndDeleteData
    },
    dispatch
  )
});

@connect(mapStateToProps, mapDispatchToProps)
class LeaveJob extends Component {
  static defaultProps = {};
  // propTypes 验证
  static propTypes = {
    actions: PropTypes.shape({
      dispatch: PropTypes.func.isRequired,
      getAllLeaveReasons: PropTypes.func.isRequired,
      leaveJobAndDelete: PropTypes.func.isRequired,
      getLeaveAndDeleteData: PropTypes.func.isRequired
    }).isRequired,
    form: PropTypes.shape({
      getFieldDecorator: PropTypes.func,
      getFieldsValue: PropTypes.func,
      setFieldsValue: PropTypes.func,
      validateFields: PropTypes.func
    })
  };

  constructor(props) {
    super(props);
    this.state = {
      name: "",
      approvalCount: "",
      pickedUsers: [],
      showAlert: true
    };
    setTitle({ title: "办理离职并删除" });
    setRight({
      show: false
    });
  }

  componentDidMount() {
    this.props.actions
      .getAllLeaveReasons({
        userId: get("userId")
      })
      .then(res => {
        const { dismissionReasonList: leaveReasons, name } = res.result;
        this.setState({
          leaveReasons,
          name
        });
      });
      this.props.actions
      .getLeaveAndDeleteData({
        userId: get("userId")
      })
      .then(res => {
        const { approvalCount = '0' } = res.result;
        this.setState({
          approvalCount
        });
      });
  }

  handleUserSelect = () => {
    // const corpId = getUrlParam("corpId");
    const corpId = get("corpId");
    // console.log(corpId)
    const { pickedUsers } = this.state;
    complexPicker({
      title: "请选择工作交接人",
      multiple: false, // 多选
      corpId,
      pickedUsers,
      responseUserOnly: true,
      cb: result => {
        const { users } = result;
        this.setState({ pickedUsers: users });
        this.props.form.setFieldsValue({ handOverUserId: users[0].name });
      },
      errCb: err => alert({ title: "出错了", message: JSON.stringify(err) })
    });
  };

  submit = () => {
    this.props.form.validateFields(err => {
      if (!err) {
        confirm({
          title: "确认删除该员工？",
          message: "删除后，该员工待处理的审批单将会转交给工作交接人，离职信息汇入成长记录",
          buttonLabels: ["取消", "删除"],
          cb: res => {
            if (res.buttonIndex === 1) {
              const values = this.props.form.getFieldsValue();
              values.handOverUserId = (this.state.pickedUsers[0] || {}).emplId || '';
              const userId = get("userId");
              if(userId === values.handOverUserId) {
                toast({
                  text: "不能交接给自己",
                });
                return;
              }
              delete values.name;
              this.props.actions
                .leaveJobAndDelete({
                  userId,
                  ...values
                })
                .then(res => {
                  if (res.success) {
                    // window.location.href = "dingtalk://dingtalkclient/action/switchtab?index=0&name=im&reload=true"
                    toast({
                      icon: 'success',
                      text: "已提交",
                      onSuccess() {
                          notify({
                            "name":"hrm_leaveJob",
                            // "data":{"a":1}
                          });
                          close();
                      }
                    });
                  }
                });
            }
          }
        });
      } else {
        showMessage(err);
      }
    });
  };

  closeAlert = () => {
    this.setState({showAlert: false});
  }
  render() {
    const {
      getFieldDecorator,
    } = this.props.form;
    const { name, approvalCount, leaveReasons, showAlert } = this.state;
    // const holidayLeft = get("holidayLeft");
    // const username = get("username");
    return (
      <div>
        <div className="scroll-body leave-job-delete step-form ">
          {showAlert && <div className="alter-card">
          <img
              src="https://img.alicdn.com/tfs/TB1kFUdar_I8KJjy1XaXXbsxpXa-1119-516.png"
              alt=""
            />
            <Icon
              color="#fff"
              type="cross"
              size="sm"
              className="close-button"
              onClick={this.closeAlert}
            />
          </div>}

          <div className="form">
            {getFieldDecorator("name", {
              initialValue: name,
              rules: [
                {
                  label: "姓名",
                  required: true,
                  validator
                }
              ]
            })(
              <InputItem clear className="input-name">
                <span className="confirm-must">*</span>姓名
              </InputItem>
            )}

            {getFieldDecorator("lastWorkDate", {
              rules: [
                {
                  label: "离职日期",
                  required: true,
                  validator
                }
              ]
            })(
              <DatePicker
                className="datepicker"
                label="离职日期"
                required
              />
            )}
            <div className="job-deliver">
              {getFieldDecorator("handOverUserId", {
                rules: [
                  {
                    label: "工作交接人",
                    required: true,
                    validator
                  }
                ]
              })(
                <InputItem
                  editable={false}
                  placeholder="请选择"
                  onClick={this.handleUserSelect}
                >
                  <span className="confirm-must">*</span>
                  工作交接人
                </InputItem>
              )}
              <Icon type="right" size="lg" className="dept-arrow-ico" />
            </div>
            <div className="divider-space">
            { approvalCount!='0'?<span>该员工尚有<span className="approval-count">{approvalCount}</span>个待处理的审批单，将会转给工作交接人</span>:'该员工待处理的审批单，将会转给工作交接人'}
            </div>

            {getFieldDecorator("dismissionReason")(
              <Select
                key="employeeType"
                options={leaveReasons}
                onChange={this.changeEmployeeType}
              >
                <span className="confirm-must" />
                离职原因
              </Select>
            )}
            {getFieldDecorator("dismissionMemo", {})(
              <TextareaItem
                title={<span className="padding-textarea">离职原因备注</span>}
                placeholder="请输入"
                rows={3}
              />
            )}
          </div>
        </div>

        <div className="scroll-btn scroll-btn-preview">
          <Button
            className="preview-button"
            type="primary"
            onClick={this.submit}
          >
            删除该员工
          </Button>
        </div>
      </div>
    );
  }
}

export default createForm()(LeaveJob);
